package com.navi.loaddata.loadService.impl.defect;

import static com.navi.loaddata.core.errorLog.ErrorCode.ERROR_ADEFECT_SQLEXCEPTION;

import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.repository.impl.GreenPlumRepositoryImpl;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * LoadAdefectService
 *
 * @author Matthew
 * @date 2018-07-14
 */
@Service
@Transactional(transactionManager = "secondaryPlatformTransactionManager",
    rollbackFor = {RuntimeException.class, Exception.class})
public class LoadAdefectService {

  private static final Logger logger = LoggerFactory.getLogger(LoadAdefectService.class);
  @Autowired
  private GreenPlumRepositoryImpl gpRepository;

  public int loadAdefectDataMain(EtlConfD etlConfD) throws ETLException2 {
    int count;
    try {
      count = loadAdefectData(etlConfD);

    } catch (ETLException2 e) {
      throw new ETLException2(ERROR_ADEFECT_SQLEXCEPTION, e);
    }
    return count;
  }
  private int loadAdefectData(EtlConfD etlConfD) throws ETLException2 {
    String startTime = etlConfD.getRunStartTimestamp().toString().substring(0, 19);
    String endTime = etlConfD.getRunEndTimestamp().toString().substring(0, 19);
    logger.info("StartTime[{}] ~ EndTime[{}]", startTime, endTime);
    String insertDefectSql = "INSERT INTO wpp_adefect_f_p SELECT * FROM wpp_adefect_f"
        + " WHERE evt_timestamp > '" + startTime + "' and evt_timestamp <= '" + endTime + "'";
    logger.info("Synchronous sql: {}", insertDefectSql);
    Query query;
    int count = 0;
    try {
      long start = System.currentTimeMillis();
      query = gpRepository.createNativeQuery(insertDefectSql);
      count = query.executeUpdate();
      long end = System.currentTimeMillis();
      logger.info("同步完成,耗时{},共同步{}条数据", end - start, count);
    } catch (Exception e) {
      e.printStackTrace();
      throw new ETLException2(ERROR_ADEFECT_SQLEXCEPTION, e);
    }
    return count;
  }

}
